package com.siae.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siae.mapper.MessageMapper;
import com.siae.pojo.Message;
import com.siae.pojo.UserItem;
import com.siae.pojo.vo.Result;
import com.siae.service.ItemService;
import com.siae.service.MessageService;
import com.siae.service.UserItemService;
import com.siae.utils.BizCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserItemService userItemService;

    @Override
    public Result<List<Message>> getAllMessages(Integer userId) {
        try {
            // 创建条件对象，设置查询条件参数
            QueryWrapper<Message> wrapper = new QueryWrapper<>();
            wrapper.eq(userId != null && userId != 0,"user_id",userId);
            // 执行查询操作
            List<Message> userItems = this.messageMapper.selectList(wrapper);
            return Result.success(BizCode.SUCCESS,userItems);
        } catch (Exception e){
            e.printStackTrace();
            log.error("查询消息信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result<Message> getMessageById(Integer id) {
        try {
            // 创建条件对象，设置查询条件参数
            QueryWrapper<Message> wrapper = new QueryWrapper<>();
            // 执行查询操作
            Message message = this.messageMapper.selectById(id);
            return Result.success(BizCode.SUCCESS,message);
        } catch (Exception e){
            e.printStackTrace();
            log.error("查询消息信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result<Integer> getMessageCount() {
        try {
            // 创建条件对象，设置查询条件参数
            QueryWrapper<Message> wrapper = new QueryWrapper<>();
            // 执行查询操作
            Long count = this.messageMapper.selectCount(wrapper);
            return Result.success(BizCode.SUCCESS,Integer.parseInt(count+""));
        } catch (Exception e){
            e.printStackTrace();
            log.error("查询消息信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result addMessage(Message message) {
        try {
            message.setIsCheck(0);
            message.setCreatedAt(new Date());
            message.setUpdatedAt(new Date());
            message.setIsDel(0);
            this.messageMapper.insert(message);
            return Result.success(BizCode.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            log.error("添加消息信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
    public Integer sendMessage(String type,Integer userId,Integer taskID){
        Message message = new Message();
        MessageTemplateServiceImpl messageTemplateService = new MessageTemplateServiceImpl();
//        message.setText(messageTemplateService.getMTemplateByName(type).getData().getId());
        message.setUserId(userId);
        message.setTaskId(taskID);
        Integer code = Integer.parseInt(addMessage(message).getData()+"");
        return code;
    }

    @Override
    public Result updateMessage(Message message) {
        try {
            if (message.getIsCheck() == 1 && message.getTaskId() != null){
                UserItem userItem = userItemService.getItemById(message.getTaskId()).getData();
                Map map = new HashMap<>();
                map.put("id",message.getTaskId());
                map.put("name",userItem.getName());
                map.put("userId",userItem.getUserId());
                map.put("userIdOne",userItem.getUserIdOne());
                map.put("userIdTwo",userItem.getUserIdTwo());
                map.put("userIdThree",userItem.getUserIdThree());
                map.put("itemId",message.getTaskId());
                map.put("createdAt",userItem.getCreatedAt());
                map.put("updatedAt",userItem.getUpdatedAt());
                map.put("isDel",userItem.getIsDel());
                if (userItem.getUserIdOne() == null){
                    map.forEach((k,v)->{
                        if (k.equals("userIdOne")){
                            v = message.getUserId();
                        }
                    });
                    userItemService.updateItem(map);
                }
                if (userItem.getUserIdTwo() == null){
                    map.forEach((k,v)->{
                        if (k.equals("userIdTwo")){
                            v = message.getUserId();
                        }
                    });
                    userItemService.updateItem(map);
                }
                if (userItem.getUserIdThree() == null){
                    map.forEach((k,v)->{
                        if (k.equals("userIdThree")){
                            v = message.getUserId();
                        }
                    });
                    userItemService.updateItem(map);
                }
            }
            message.setUpdatedAt(new Date());
            this.messageMapper.updateById(message);
            return Result.success(BizCode.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            log.error("修改消息信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result deleteMessage(Integer id) {
        try {
            this.messageMapper.deleteById(id);
            return Result.success(BizCode.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            log.error("删除消息信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result deleteMessages(String ids) {
        try {
            String[] strs = ids.split(",");
            List<Integer> idList = new ArrayList<>();
            for (String str : strs) {
                idList.add(Integer.parseInt(str));
            }
            this.messageMapper.deleteBatchIds(idList);
            return Result.success(BizCode.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            log.error("批量删除消息信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
}
